package com.interview.javac;



import javax.tools.*;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;

import static javax.tools.StandardLocation.CLASS_OUTPUT;
import static javax.tools.StandardLocation.CLASS_PATH;

public class CompileString {

	public static void main(String[] args) throws IOException {
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

		DiagnosticCollector<JavaFileObject> diagnostics =
				new DiagnosticCollector<>();

		StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
		String classes = System.getProperty("user.dir")+"/compile/javac/target/classes";
		File classesFile = new File(classes);

		fileManager.setLocation(CLASS_OUTPUT,Arrays.asList(classesFile));


		JavaStringObject stringObject =
				new JavaStringObject("Test.java", getSource());

		JavaCompiler.CompilationTask task = compiler.getTask(null,
				fileManager, diagnostics, null, null, Arrays.asList(stringObject));
		boolean success = task.call();
		System.out.println(success?"编译成功":"编译失败");
		diagnostics.getDiagnostics().forEach(System.out::println);


	}


	public static String getSource() {
		return " public class Test {"
				+ "}";
	}
}
